package com.shujia.scala

import scala.io.Source

object Demo22Student {
  def main(args: Array[String]): Unit = {
    /**
      *
      * 1、统计班级人数
      *
      */

    //1 读取数据
    val lines: List[String] = Source.fromFile("scala/data/students.txt").getLines().toList


    //2 取出班级
    val clzzs: List[String] = lines.map(line => line.split(",")(4))


    //3 按照班级进行分组
    val groupList: Map[String, List[String]] = clzzs.groupBy(clazz => clazz)


    //4\ 统计班级的人数

    val clazzNUm: Map[String, Int] = groupList.map(kv => {
      val clazz: String = kv._1

      val values: List[String] = kv._2


      //班级人数
      val num: Int = values.length


      (clazz, num)
    })


    clazzNUm.foreach(println)

    println("=" * 100)


    /**
      * 2、统计学生的总分
      *
      */

    //1 读取数据
    val scores: List[String] = Source.fromFile("scala/data/score.txt").getLines().toList

    //2 将每一行转换成样例类的对象

    val scos: List[Score] = scores.map(line => {
      val split: Array[String] = line.split(",")
      val sId: String = split(0)
      val cId: String = split(1)
      val sco: Int = split(2).toInt

      //最后一样作为返回值
      Score(sId, cId, sco)
    })


    //3 按照学号分组
    val groupList1: Map[String, List[Score]] = scos.groupBy(sco => sco.sId)


    //4 统计学生的分数
    val stuSumScore: Map[String, Int] = groupList1.map(kv => {
      val id: String = kv._1
      val scoss: List[Score] = kv._2


      //取出分数列

      val scoress: List[Int] = scoss.map(s => s.sco)

      //统计总分
      val sumSCore: Int = scoress.sum


      (id, sumSCore)
    })

    stuSumScore.foreach(println)


  }

  case class Score(sId: String, cId: String, sco: Int)

}
